let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let session = require('express-session');
let bodyParser =require('body-parser');
let logger = require('morgan');
let route = require('./app/route');
let fs = require('fs');
let FileStreamRotator = require('file-stream-rotator');
let nunjucks = require('./app/middleware/nunjucks');
let loopEvent = require('./app/common/backup_sql')

let app = express();


//*****************************  log**************************** */
let logDirectory = path.join(__dirname, 'log')

// ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)

// create a rotating write stream
let accessLogStream = FileStreamRotator.getStream({
  date_format: 'YYYYMMDD',
  filename: path.join(logDirectory, 'access-%DATE%.log'),
  frequency: 'daily',
  verbose: false
})
// 自定义时间
logger.token('localDate', function(req, res){
  let date = new Date();
  return date.toLocaleString();
});

logger.format('apiLog', ':remote-addr - :remote-user [:localDate] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"');

app.use(logger('apiLog', {stream: accessLogStream}))
// uncomment after placing your favicon in /public
app.use(logger('dev'));
//*****************************  log**************************** */
app.use(bodyParser.json({limit:'50mb'}));
app.use(bodyParser.urlencoded({limit:'50mb', extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'upload')));
// app.use(express.static(path.join(__dirname, 'apidoc')));

// 设置跨域访问，
app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*'); //*代表可访问的地址，可以设置指定域名
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
      if (req.method == 'OPTIONS') {
      res.json({status:200}); 
    }
    else {
      next();
    }
  });
  app.use(session({
    secret: 'attendance',
    resave: true,
    saveUninitialized: false,
    cookie: {
      maxAge: 3 * 60 * 60 * 1000,
    },
  }));
  //错误异常捕获处理
  process.on('unhandledRejection', error => {
    console.error('unhandledRejection', error);
    process.exit(1) // To exit with a 'failure' code
  });


  //loopEvent();
  nunjucks(app);

route.route(app);

module.exports = app;

//事件监听
